import qs from "qs";
import * as http from "@/utils/sgmw_auth/http";

/**
 *获取用户Token
 * @param code 临时授权码
 * @returns token
 */
export function accessToken(code: string) {
  let requestUri = `${import.meta.env.VITE_APP_OidcUrl}token`;
  let clientid = import.meta.env.VITE_APP_OidcId;
  const grantType = "authorization_code";
  const redirectUri =
    window.location.origin + import.meta.env.VITE_APP_OidcRedirect;
  let data = {
    client_id: clientid,
    code,
    grant_type: grantType,
    redirect_uri: redirectUri
  };
  console.log(data);
  return http.requestPost<any>(requestUri, qs.stringify(data), {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  });
}

/**
 * 获取用户信息
 * @param token 用户认证token
 * @returns 用户信息
 */
export function getUserInfo(token: string) {
  let OidcUrl = import.meta.env.VITE_APP_OidcUrl;
  let url = `/master/oidc/refreshUserToken`;
  return http.requestPostForm(url, qs.stringify({ token, url: OidcUrl }));
}

/**
 * 获取用户信息
 * @param token 用户认证token
 * @returns 用户信息
 */
export function getUserProfile(token: string) {
  let OidcUrl = import.meta.env.VITE_APP_OidcUrl;
  let url = `/master/oidc/RefreshProfileToken`;
  return http.requestPostForm(url, qs.stringify({ token, url: OidcUrl }));
}
/**
 * 用户授权认证登出
 * @param token 用户刷新token
 * @returns 请求成功返回状态码204
 */
export function logout(token: string) {
  let url = `${import.meta.env.VITE_APP_OidcUrl}logout`;
  let data = {
    refresh_token: token,
    client_id: import.meta.env.VITE_APP_OidcId
  };
  return http.requestPostForm(url, data);
}
